#pragma once
#include <iostream>
#include <cstdio>
#include <functional>

class CalTask
{
    using func_t = std::function<int(int, int, char)>; // func是一个函数
    // typedef std::function<int(int,int)> func;
public:
    CalTask() {}

    CalTask(int x, int y, char op, func_t func)
        : _x(x), _y(y), _op(op), _callback(func) {}

    std::string operator()()
    {
        int result = _callback(_x, _y, _op);
        char buffer[1024];
        snprintf(buffer, sizeof(buffer) - 1, "%d %c %d = %d", _x, _op, _y, result);
        return buffer;
    }

    // 返回任务操作的结果
    std::string toString()
    {
        char buffer[1024];
        snprintf(buffer, sizeof(buffer) - 1, "%d %c %d = ?", _x, _op, _y);
        return buffer;
    }

private:
    int _x;
    int _y;
    char _op;         // 操作的任务的id
    func_t _callback; // 调用的函数
};

class SaveTask
{
    typedef std::function<void(const std::string &)> func_t;

public:
    SaveTask() {}
    SaveTask(const std::string &message, func_t func)
        : _message(message), _callback(func) {}
    void operator()()
    {
        _callback(_message);
    }

private:
    std::string _message; // 保存的信息
    func_t _callback;     // 将信息写入文件中
};

const std::string oper = "+-*/%";
int my_math(int x, int y, char op)
{
    int result = 0;
    switch (op)
    {
    case '+':
        result = x + y;
        break;
    case '-':
        result = x - y;
        break;
    case '*':
        result = x * y;
        break;
    case '/':
    {
        if (y == 0)
        {
            std::cerr << "div zero" << std::endl;
            return -1;
        }
        else
        {
            result = x / y;
        }
        break;
    }
    case '%':
        if (y == 0)
        {
            std::cerr << "moved zero" << std::endl;
            return -1;
        }
        else
        {
            result = x % y;
        }
        break;
    default:
        break;
    }
    return result;
}

void Save(const std::string &message)
{
    const std::string task_pwd = "./log.txt";
    FILE *fp = fopen(task_pwd.c_str(), "a+");
    if (nullptr == fp)
    {
        std::cerr << "saver open error" << std::endl;
        return;
    }
    fputs(message.c_str(), fp);
    fputc('\n', fp);

    fclose(fp);
}